<template>
  <el-form
        ref="ruleFormRef"
        :model="formData"
        :rules="formRules"
        size="small"
        :inline="false"
        label-width="100px"
    >
      <el-form-item label="主题" prop="title">
        <el-input
            v-model="formData.title"
            placeholder="请输入主题"
            maxlength="32"
            size="small"
        />
      </el-form-item>
      <el-form-item label="候选人" prop="candidateId">
        <el-select
            v-model="formData.candidateId"
            placeholder="请选择候选人"
            @change="candidateChange"
            size="small"
            filterable
        >
          <el-option
              v-for="item in candidateList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="面试时间" prop="actionTime">
        <div style="max-width: 400px">
          <el-date-picker
              v-if="dateType"
              v-model="interviewTimeRange"
              type="datetimerange"
              range-separator="-"
              size="small"
              start-placeholder="面试开始时间"
              end-placeholder="面试结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="interviewTimeSelected"
          />
          <el-date-picker
              v-else
              v-model="formData.actionStartTime"
              type="datetime"
              style="width: 100%"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择会议时间"
          />
        </div>
        <el-button style="margin-left: 10px" plain :icon="Refresh" @click="dateType = !dateType"/>
      </el-form-item>
      <el-form-item label="面试官" prop="executorIds">
        <el-select
            v-model="formData.executorIds"
            placeholder="请选择面试官"
            multiple
            size="small"
            filterable
        >
          <el-option
              v-for="item in relatorList"
              :key="item.userId"
              :value="item.userId"
              :label="item.nickname"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="联系人" prop="contactUserId">
        <el-select
            v-model="formData.contactUserId"
            placeholder="请选择联系人"
            @change="contactChange"
            size="small"
            filterable
        >
          <el-option
              v-for="item in relatorList"
              :key="item.userId"
              :value="item.userId"
              :label="item.nickname"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input
            v-model="formData.contactPhone"
            placeholder="请输入联系电话"
            maxlength="16"
            size="small"
        />
      </el-form-item>
      <el-form-item label="面试方式" prop="interviewType">
        <el-select
            v-model="formData.interviewType"
            placeholder="请选择面试方式"
            size="small"
        >
          <el-option
              v-for="item in dictMap['InterviewType']"
              :key="item.value"
              :label="item.name"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="优先度">
        <el-radio-group v-model="formData.priority">
          <el-radio :label="0" size="small">普通</el-radio>
          <el-radio :label="1" size="small">高</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="通知时间" prop="remindState">
        <el-radio-group v-model="formData.remindState">
          <el-radio
              v-for="item in remindTimes"
              :key="item.value"
              :label="item.value"
              size="small"
          >{{ item.label }}
          </el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item label="通知方式" prop="remindType">
        <el-checkbox-group v-model="formData.remindType" size="small">
          <el-checkbox label="1">应用、公众号通知</el-checkbox>
          <el-checkbox label="2">短信通知</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
</template>

<script>
// OA_PLAN_INTERVIEW 安排面试
import {onMounted, reactive, toRefs, ref, nextTick, watch} from 'vue'
import {homeApi} from '/@/api/home/index'
import {getListByType, getInterviewerIds} from '/@/api/oa/candidate'
import {getDictByCodes} from '/@/api/sys/dict'
import {getEnterpriseUsers} from '/@/api/sys/user'
import {getRemindTimes} from '/@/api/matter'
import {Refresh} from '@element-plus/icons-vue'
import { useCalendarConfig } from '/@/stores/calendar';
import { storeToRefs } from 'pinia';

export default {
    name: 'PlanInterviewForm',
    props: {
        selectTime: {
            type: String,
            default: null
        },
        idw: {
            type: String,
            default: null
        },
        editId: {
          type: String,
          default: null
        }
    },
    setup(props) {
        const { idw, editId } = toRefs(props)
        const homeCalendar = homeApi()
        const ruleFormRef = ref({})
        const storesCalendarConfig = useCalendarConfig();
        const { eventForm } = storeToRefs(storesCalendarConfig)
        const state = reactive({
            code: 'OA_PLAN_INTERVIEW',
            formData: {
                candidateId: null,
                executorIds: [], // 面试官?
                title: '安排面试',
                content: '',
                state: 0, // 状态 -1草稿 0未开始 1进行中 2已完成 3已退回  4已取消 5已撤回
                priority: 0, // 优先级 0普通 1重要
                actionStartTime: null, // 面试开始时间
                actionEndTime: null, // 面试结束时间
                contactUserId: null, // 联系人id
                contactPhone: null, // 联系人电话
                interviewType: null, // 面试方式
                remindState: 'NONE', // 提醒时间, 根据枚举类MatterRemindTimeEnum
                remindType: [] // 提醒方式, 多选
            },
            formRules:{
                candidateId: {
                    required: true,
                    message: '请选择候选人',
                    trigger: 'change'
                },
                title: {
                    required: true,
                    message: '请输入主题',
                    trigger: 'blur'
                },
                executorIds: {
                    required: true,
                    message: '请选择面试官',
                    trigger: 'change'
                },
                actionStartTime: {
                    required: true,
                    message: '请选择面试开始时间',
                    trigger: 'change'
                }
            },
            interviewTimeRange: [], // 面试时间范围
            dateType: true,
            dictMap: {},
            candidateList: [],
            relatorList: [],
            remindTimes: [],
            originForm: {}
        })
        const reset =  () => {
            if (!ruleFormRef) return
            ruleFormRef.value.resetFields()
        }
        const submit = () => {
             if (!ruleFormRef) return
             return new Promise(async (resolve,  reject) => {
              await ruleFormRef.value.validate((valid, fields) => {
                  if (valid) {
                    let str = state.formData.remindType.join(',')
                    state.formData.remindType = str
                    if(editId.value) {
                      // 编辑
                      for(let key in state.formData){
                        if(state.originForm.hasOwnProperty(key)){
                          state.originForm[key] = state.formData[key]
                        }
                        if(state.originForm.info.hasOwnProperty(key)){
                          state.originForm.info[key] = state.formData[key]
                        }
                      }
                      storesCalendarConfig.setEventForm(state.originForm)
                      resolve('edit') 
                    } else {
                      homeCalendar.addPlanInterview(state.formData).then((res) => {
                        if (res.code === 0) {
                          reset()
                          context.emit('closeForm')
                          resolve()
                        }
                      }).catch(e => reject(e))
                    }
                    
                  } else {
                    console.log('error submit!', fields)
                  }
                })
             })
             
        }
        const handleDefaultInterviewers = async () => {
            try {
                const res = await getInterviewerIds(state.formData.candidateId)
                if (res.data && res.data.length > 0) {
                state.formData.executorIds = Object.assign([], res.data)
                }
            } catch (e) {
                console.log(e)
            }
        }
        const getCandidateData = async () => {
            // 获取初筛通过的
            try {
                const res = await getListByType('1')
                state.candidateList = res.data
            } catch (e) {
                console.log(e)
            }
        }
        const getRelatorData = async () => {
            // 面试官和联系人共用数据
            const res = await getEnterpriseUsers()
            state.relatorList = res.data
        }
        const interviewTimeSelected = (selectedTime) => {
            if (selectedTime && selectedTime.length == 2) {
                let nowTime = new Date()
                state.formData.actionStartTime = selectedTime[0]
                state.formData.actionEndTime = selectedTime[1]
                if (nowTime > new Date(selectedTime[0])) {
                // 现在时间小于/等于面试开始时间就是未开始, 大于才有可能是进行中/已完成
                state.formData.state = nowTime < selectedTime[1] ? 1 : 2
                }
            } else {
                state.formData.actionStartTime = state.formData.actionEndTime = null
            }
        }
        const getRemindData = async () => {
            try {
                const res = await getRemindTimes()
                state.remindTimes = res.data
            } catch (e) {
                console.log(e)
            }
        }
        const candidateChange = (val) => {
            if (val) {
                handleDefaultInterviewers()
            }
        }
        const contactChange = async (val) => {
            // 选择联系人后自动带入手机号
            for (let i = 0; i < state.relatorList.length; i++) {
                if (state.relatorList[i].userId == val) {
                  state.formData.contactPhone = state.relatorList[i].phone
                  break
                }
            }
        }
        watch(() => eventForm.value,
          val => {
            if(editId.value && val) {
              // 编辑
              nextTick(() => {
                const data = val
                if(!data) return
                state.originForm = data
                for(let params in data.info){
                  // 拿出info里面的数据
                  if(state.formData.hasOwnProperty(params)) {
                    state.formData[params] = data.info[params]
                  }
                }
                for(let key in data) {
                  // 列表里面的数据
                  if(state.formData.hasOwnProperty(key)) {
                    state.formData[key]= data[key]
                  }
                }
                if(data.actionStartTime && data.actionEndTime) {
                  // 时间组合
                  state.interviewTimeRange = [data.actionStartTime, data.actionEndTime]
                }
                if(data.remindType){
                  state.formData.remindType = data.remindType.split(',')
                }
              })
            }
          }        
        )
        onMounted(() => {
            getDictByCodes(['InterviewType']).then((res) => (state.dictMap = res.data))
            getCandidateData()
            getRelatorData()
            getRemindData()
            if (state.formData.candidateId) {
                handleDefaultInterviewers()
            }
        })
        return {
            ...toRefs(state),
            ruleFormRef,
            reset,
            submit,
            interviewTimeSelected,
            getRemindData,
            candidateChange,
            contactChange,
            Refresh
        }
    }
}
</script>

<style>

</style>